import CodeEditor from '@uiw/react-textarea-code-editor';
import { Button, Card, message } from 'antd';
import { useState } from 'react';
import YAML from "yamljs";
import TOML from "@iarna/toml";
import { writeText } from '@tauri-apps/api/clipboard';

function TomlPanel() {
    const [jsonValue, setJsonValue] = useState("");
    const [yamlValue, setYamlValue] = useState("");
    const [tomlValue, setTomlValue] = useState("");
    const [errStr, setErrstr] = useState("");

    return (
        <Card title="Toml转换" bordered={false} bodyStyle={{ height: "calc(100vh - 100px)", overflowY: "auto" }}>
            <Card title="Toml源内容" bordered={false}>
                <CodeEditor lang='toml' value={tomlValue}
                    style={{ height: "200px", overflowY: "auto" }}
                    onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setTomlValue(e.target.value);
                        try {
                            const obj = TOML.parse(e.target.value);
                            setJsonValue(JSON.stringify(obj, undefined, 2));
                            setYamlValue(YAML.stringify(obj, undefined, 2));
                            setErrstr("");
                        } catch (e) {
                            setErrstr(`${e}`)
                        }
                    }} />
                {errStr != "" && (
                    <p style={{ color: "red" }}>{errStr}</p>
                )}
            </Card>
            <Card title="Json目标内容" bordered={false} extra={
                <Button onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    writeText(jsonValue).then(() => message.info("复制成功"));
                }}>复制json内容</Button>
            }>
                <CodeEditor lang='json' value={jsonValue} disabled
                    style={{ height: "200px", overflowY: "auto" }} />
            </Card>
            <Card title="Yaml目标内容" bordered={false} extra={
                <Button onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    writeText(yamlValue).then(() => message.info("复制成功"));
                }}>复制yaml内容</Button>
            }>
                <CodeEditor lang='yaml' value={yamlValue} disabled
                    style={{ height: "200px", overflowY: "auto" }} />
            </Card>
        </Card>
    );
}

export default TomlPanel;